<template>
  <view class="container">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <image class="user-avatar" :src="userInfo.avatar || '/img/人力招聘.svg'" mode="aspectFit" @click="handleAvatarClick"></image>
      <view class="user-info">
        <text class="username">用户名：{{ userInfo.username }}</text>
      </view>
      <wd-icon class="setting-icon" name="setting" size="22px" @click="handleSetting"></wd-icon>
    </view>

    <!-- 功能入口 -->
    <view class="function-grid">
      <view class="function-item" @click="MyOrder(1)">
        <!-- <wd-icon name="setting" size="28px" color="#e3d26e"></wd-icon> -->
		<image src="/img/订单管理.svg" mode=""></image>
        <text class="function-text">我的订单</text>
      </view>
      <view class="function-item" @click="addressAdministration(2)">
        <!-- <wd-icon name="setting" size="28px" color="#67C23A"></wd-icon> -->
		<image src="/img/地址管理.svg" mode=""></image>
        <text class="function-text">地址管理</text>
      </view>
      <view class="function-item" @click="handleFunction(3)">
        <!-- <wd-icon name="setting" size="28px" color="#E6A23C"></wd-icon> -->
			<image src="/img/历史足迹.svg" mode=""></image>
        <text class="function-text">历史足迹</text>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-section">
      <view class="section-header">
        <text class="section-title">我的订单</text>
        <text class="section-more">查看全部 ></text>
      </view>
      <view class="order-grid">
        <view class="order-item" @click="handleOrder(1)">
          <!-- <wd-icon name="setting" size="24px" color="#909399"></wd-icon> -->
		  <image src="/img/我的－待付款.svg" mode=""></image>
          <text class="order-text">待付款</text>
        </view>
        <view class="order-item" @click="handleOrder_drop(2)">
          <!-- <wd-icon name="setting" size="24px" color="#909399"></wd-icon> -->
		  <image src="/img/首页-待发货.svg" mode=""></image>
          <text class="order-text">待发货</text>
        </view>
        <view class="order-item" @click="handleOrder(3)">
         <!-- <wd-icon name="setting" size="24px" color="#909399"></wd-icon> -->
		 <image src="/img/待收货.svg" mode=""></image>
          <text class="order-text">待收货</text>
        </view>
      </view>
    </view>

    <wd-divider>其他信息</wd-divider>

    <!-- 商品列表区域 -->
    <view class="product-section">
      <view class="section-header">
        <text class="section-title">推荐商品</text>
        <text class="section-more">查看更多 ></text>
      </view>
      
      <view class="product-list">
        <!-- 商品项 -->
        <view class="product-item" v-for="item in products" :key="item.id" @click="handleProductClick(item)">
          <image class="product-image" :src="item.img_url || '/static/logo.png'" mode="aspectFill"></image>
          <view class="product-info">
            <text class="product-name">{{ item.title }}</text>
            <text class="product-desc">{{ item.zhaiyao }}</text>
            <view class="product-bottom">
              <text class="product-price">¥{{ item.sell_price }}</text>
              <text class="product-market"
                style="text-decoration:line-through;color:#bbb;font-size:12px;margin-left:8rpx;">¥{{ item.market_price }}</text>
              <wd-icon name="cart" size="20px" color="#F56C6C"></wd-icon>
            </view>
          </view>
        </view>
        <!-- 无商品时显示 -->
        <view v-if="products.length === 0" class="empty-box">
          <image src="@/img/暂无商品.svg" class="empty-img" mode="widthFix" />
          <text class="empty-text">暂无产品</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { request, BASE_URL } from '@/Requset/request'

// 响应式数据
const products = ref([])
const userInfo = ref({
  username: '未登录',
  avatar: ''
})

// 获取用户信息
const getUserInfo = () => {
  try {
    const userInfoStr = uni.getStorageSync('userInfo')
    if (userInfoStr) {
      const info = JSON.parse(userInfoStr)
      // 头像路径处理
      if (info.avatar && !/^https?:\/\//.test(info.avatar)) {
        info.avatar = BASE_URL + info.avatar
      }
      userInfo.value = info
    }
  } catch (e) {
    console.error('获取用户信息失败:', e)
  }
}

// 获取推荐商品
const fetchProducts = () => {
  request({
    url: 'api/recommend?page=1&limit=10'
  }).then((res) => {
    if (res.data && res.data.status === 0 && Array.isArray(res.data.message)) {
      products.value = res.data.message
    } else {
      products.value = []
    }
  })
}

// 保存浏览历史
const saveHistory = (item) => {
  let history = uni.getStorageSync('history') || []
  history = history.filter(i => i.id !== item.id)
  history.unshift(item)
  if (history.length > 20) history = history.slice(0, 20)
  uni.setStorageSync('history', history)
}

// 事件处理函数
const handleSetting = () => {
  uni.navigateTo({
    url: '/pages/settingUp/settingUp'
  })
}

const handleFunction = (index) => {
  console.log('功能按钮被点击:', index)
  uni.navigateTo({
    url: '/pages/history/history'
  })
}

const addressAdministration = (index) => {
  console.log('地址管理按钮被点击:', index)
  uni.navigateTo({
    url: '/pages/address/address'
  })
}

const handleOrder = (type) => {
  console.log('订单类型被点击:', type)
  // 跳转到对应订单列表页面，并传递类型参数
  uni.navigateTo({
    url: '/pages/obligation/obligation?type=0'
  })
}

const handleOrder_drop = (type) => {
  console.log('待发货被点击:', type)
  uni.navigateTo({
    url: '/pages/drop_shipping/drop_shipping'
  })
}

const MyOrder = (index) =>{
	console.log('我的订单被点击:', index)
	uni.navigateTo({
	  url: '/pages/MyOrder_page/MyOrder_page'
	})
}
const handleProductClick = (item) => {
  saveHistory(item)
  uni.navigateTo({
    url: `/pages/detail/detail?id=${item.id}`
  })
}

// 头像上传处理
const handleAvatarClick = async () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: async (chooseRes) => {
      console.log('选择图片结果:', chooseRes)
      const filePath = chooseRes.tempFilePaths[0]
      const token = uni.getStorageSync('token')
      uni.uploadFile({
        url: BASE_URL + 'api/upload',
        filePath,
        name: 'avatar',
        header: { token },
        formData: {},
        success: (uploadRes) => {
          console.log('上传接口原始返回:', uploadRes)
          try {
            const data = JSON.parse(uploadRes.data)
            console.log('解析后的 data:', data)
            if (data.status === 0 && data.src) {
              let avatarUrl = data.src
              // 如果不是完整的 http/https 路径，拼接 BASE_URL
              if (!/^https?:\/\//.test(avatarUrl)) {
                avatarUrl = BASE_URL + avatarUrl
              }
              userInfo.value.avatar = avatarUrl
              uni.setStorageSync('userInfo', JSON.stringify(userInfo.value))
              uni.showToast({ title: '头像上传成功', icon: 'success' })
              setTimeout(() => {
                getUserInfo()
                console.log('刷新后头像地址:', userInfo.value.avatar)
              }, 300)
            } else {
              uni.showToast({ title: data.message || '上传失败', icon: 'none' })
            }
          } catch (e) {
            console.error('解析上传返回失败:', e)
          }
        },
        fail: (err) => {
          console.error('上传失败:', err)
          uni.showToast({ title: '上传失败', icon: 'none' })
        }
      })
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
    }
  })
}

// 生命周期钩子
onMounted(() => {
  fetchProducts()
  getUserInfo()
})

onShow(() => {
  getUserInfo()
})
</script>

<style lang="scss" scoped>
@import '@/common/common.scss';

.container {
  padding: #{px2rpx(10)};
  background-color: #f5f7fa;
}

/* 用户卡片样式 */
.user-card {
  display: flex;
  align-items: center;
  padding: #{px2rpx(15)};
  background: linear-gradient(135deg, #55aaff, #55aaff);
  border-radius: #{px2rpx(8)};
  box-shadow: 0 #{px2rpx(2)} #{px2rpx(6)} rgba(64, 158, 255, 0.2);
  margin-bottom: #{px2rpx(15)};
  color: white;
}

.user-avatar {
  width: #{px2rpx(50)};
  height: #{px2rpx(50)};
  border-radius: 50%;
  border: #{px2rpx(2)} solid rgba(255, 255, 255, 0.3);
  margin-right: #{px2rpx(10)};
}

.user-info {
  flex: 1;
}

.username {
  font-size: #{px2rpx(16)};
  font-weight: bold;
}

.setting-icon {
  padding: #{px2rpx(5)};
}

/* 功能入口样式 */
.function-grid {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
}

.function-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 10rpx;
}

.function-item image {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 8rpx;
  object-fit: contain;
}

.function-text {
  font-size: 26rpx;
  color: #606266;
  margin-top: 2rpx;
  text-align: center;
}

/* 订单区域样式 */
.order-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 18rpx 0 10rpx 0;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 18rpx 10rpx 18rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #303133;
}

.section-more {
  font-size: 24rpx;
  color: #909399;
}

.order-grid {
  display: flex;
  justify-content: space-between;
  padding: 0 18rpx;
}

.order-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.order-item image {
  width: 48rpx;
  height: 48rpx;
  margin-bottom: 6rpx;
  object-fit: contain;
}

.order-text {
  font-size: 24rpx;
  color: #606266;
  margin-top: 2rpx;
  text-align: center;
}

/* 商品列表样式 */
.product-section {
  background-color: white;
  border-radius: #{px2rpx(8)};
  padding: #{px2rpx(10)};
  box-shadow: 0 #{px2rpx(1)} #{px2rpx(4)} rgba(0, 0, 0, 0.05);
  margin-bottom: #{px2rpx(15)};
}

.product-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.product-item {
  width: 48%;
  margin-bottom: #{px2rpx(10)};
  border-radius: #{px2rpx(6)};
  overflow: hidden;
  background: #fff;
  box-shadow: 0 #{px2rpx(1)} #{px2rpx(4)} rgba(0, 0, 0, 0.08);
}

.product-image {
  width: 100%;
  height: #{px2rpx(150)};
  background-color: #f5f5f5;
}

.product-info {
  padding: #{px2rpx(7.5)};
}

.product-name {
  font-size: #{px2rpx(13)};
  color: #333;
  font-weight: bold;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  margin-bottom: #{px2rpx(4)};
}

.product-desc {
  font-size: #{px2rpx(11)};
  color: #999;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  margin-bottom: #{px2rpx(7.5)};
}

.product-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: #{px2rpx(14)};
  color: #F56C6C;
  font-weight: bold;
}

.empty-box {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
}

.empty-img {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}
</style>